<template>
  <div class="inventory-snapshot-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>生产绩效</span>
          <div class="header-operations">
            <el-date-picker
              v-model="snapshotDate"
              type="datetime"
              placeholder="选择快照时间点"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
            />
            <el-button type="primary" @click="handleQuery">查询快照</el-button>
            <el-button type="success" @click="handleCreateSnapshot"
              >生成快照</el-button
            >
            <el-button type="primary" @click="handleExport">导出快照</el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" :model="queryForm" class="search-form">
        <el-form-item label="物料编码">
          <el-input
            v-model="queryForm.materialCode"
            placeholder="请输入物料编码"
          />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input
            v-model="queryForm.materialName"
            placeholder="请输入物料名称"
          />
        </el-form-item>
        <el-form-item label="仓库">
          <el-select
            v-model="queryForm.warehouse"
            placeholder="请选择仓库"
            clearable
          >
            <el-option
              v-for="item in warehouseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="正常" value="normal" />
            <el-option label="冻结" value="frozen" />
            <el-option label="待检" value="pending" />
            <el-option label="不合格" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 快照时间点列表 -->
      <div class="snapshot-list" v-if="showSnapshotList">
        <div class="list-header">
          <span>历史快照时间点</span>
          <el-button link @click="showSnapshotList = false">收起</el-button>
        </div>
        <el-scrollbar height="150px">
          <div
            v-for="item in snapshotList"
            :key="item.time"
            class="snapshot-item"
            :class="{ active: item.time === snapshotDate }"
            @click="handleSelectSnapshot(item)"
          >
            <span>{{ item.time }}</span>
            <span class="snapshot-info">
              <el-tag
                size="small"
                :type="item.type === 'auto' ? 'info' : 'success'"
              >
                {{ item.type === "auto" ? "自动" : "手动" }}
              </el-tag>
              <span class="creator">{{ item.creator }}</span>
            </span>
          </div>
        </el-scrollbar>
      </div>
      <el-button
        v-else
        link
        type="primary"
        class="show-list-btn"
        @click="showSnapshotList = true"
      >
        显示历史快照列表
      </el-button>

      <!-- 快照数据表格 -->
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        :summary-method="getSummary"
        show-summary
      >
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.batchList" border>
              <el-table-column prop="batchNo" label="批次号" />
              <el-table-column prop="manufactureDate" label="生产日期" />
              <el-table-column prop="expiryDate" label="有效期至" />
              <el-table-column prop="quantity" label="数量" />
              <el-table-column prop="location" label="库位" />
              <el-table-column prop="status" label="状态">
                <template #default="scope">
                  <el-tag :type="getStatusType(scope.row.status)">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="materialCode" label="物料编码" width="150" />
        <el-table-column prop="materialName" label="物料名称" min-width="150" />
        <el-table-column prop="specification" label="规格型号" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="warehouse" label="仓库" width="120" />
        <el-table-column prop="totalQuantity" label="库存数量" width="100" />
        <el-table-column
          prop="availableQuantity"
          label="可用数量"
          width="100"
        />
        <el-table-column prop="lockedQuantity" label="锁定数量" width="100" />
        <el-table-column prop="price" label="单价" width="100" />
        <el-table-column prop="amount" label="金额" width="120" />
        <el-table-column prop="lastUpdate" label="最后更新" width="180" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 生成快照对话框 -->
      <el-dialog
        v-model="createDialogVisible"
        title="生成生产绩效"
        width="500px"
      >
        <el-form
          :model="createForm"
          label-width="100px"
          :rules="rules"
          ref="createFormRef"
        >
          <el-form-item label="快照说明" prop="description">
            <el-input
              v-model="createForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入快照说明"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="createDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleCreateSubmit"
              >确定</el-button
            >
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 状态定义
const snapshotDate = ref("");
const showSnapshotList = ref(false);
const createDialogVisible = ref(false);
const createForm = ref({
  description: "",
});

// 查询表单
const queryForm = ref({
  materialCode: "",
  materialName: "",
  warehouse: "",
  status: "",
});

// 表格数据
const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 快照列表
const snapshotList = ref([
  {
    time: "2024-03-20 00:00:00",
    type: "auto",
    creator: "System",
  },
  {
    time: "2024-03-19 15:30:00",
    type: "manual",
    creator: "Admin",
  },
]);

// 日期时间选择限制
const disabledDate = (time) => {
  return time.getTime() > Date.now();
};

const disabledTime = (date) => {
  if (date) {
    const currentDate = new Date();
    const selectedDate = new Date(date);

    if (selectedDate.toDateString() === currentDate.toDateString()) {
      return {
        hours: [...Array(24).keys()].slice(currentDate.getHours() + 1),
        minutes: [...Array(60).keys()].slice(currentDate.getMinutes() + 1),
        seconds: [...Array(60).keys()].slice(currentDate.getSeconds() + 1),
      };
    }
  }
  return {
    hours: [],
    minutes: [],
    seconds: [],
  };
};

// 获取状态样式
const getStatusType = (status) => {
  const map = {
    normal: "success",
    frozen: "info",
    pending: "warning",
    rejected: "danger",
  };
  return map[status] || "";
};

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    normal: "正常",
    frozen: "冻结",
    pending: "待检",
    rejected: "不合格",
  };
  return map[status] || status;
};

// 表格合计行
const getSummary = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

// 查询方法
const handleSearch = () => {
  // 实现查询逻辑
};

const handleReset = () => {
  queryForm.value = {
    materialCode: "",
    materialName: "",
    warehouse: "",
    status: "",
  };
  handleSearch();
};

// 快照相关方法
const handleQuery = () => {
  if (!snapshotDate.value) {
    ElMessage.warning("请选择快照时间点");
    return;
  }
  // 实现快照查询逻辑
};

const handleCreateSnapshot = () => {
  createForm.value.description = "";
  createDialogVisible.value = true;
};

const handleCreateSubmit = () => {
  // 实现快照生成逻辑
  ElMessage.success("快照生成成功");
  createDialogVisible.value = false;
  // 刷新快照列表
};

const handleSelectSnapshot = (snapshot) => {
  snapshotDate.value = snapshot.time;
  handleQuery();
};

// 导出方法
const handleExport = () => {
  if (!snapshotDate.value) {
    ElMessage.warning("请先选择快照时间点");
    return;
  }
  // 实现导出逻辑
  ElMessage.success("导出成功");
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  handleSearch();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  handleSearch();
};
</script>

<style scoped>
.inventory-snapshot-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

.snapshot-list {
  margin-bottom: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.list-header {
  padding: 10px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #dcdfe6;
}

.snapshot-item {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
}

.snapshot-item:last-child {
  border-bottom: none;
}

.snapshot-item:hover {
  background-color: #f5f7fa;
}

.snapshot-item.active {
  background-color: #ecf5ff;
}

.snapshot-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.creator {
  color: #909399;
  font-size: 13px;
}

.show-list-btn {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>
